package com.xiaoluyy.demo.config;

import com.alibaba.druid.pool.DruidDataSource;
//import com.xiaoluyy.mybatis.SqlMonitorManager;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.util.ClassUtils;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;

/*
 * myBatis configuration
 *  @see http://mybatis.github.io/spring/mappers.html
 */
@Configuration
@MapperScan(basePackages = "com.xiaoluyy.demo.core.dao")
@EnableTransactionManagement
public class MybatisConfig {

	private static Logger log = LoggerFactory.getLogger(MybatisConfig.class);

	@Value("${datasource.driverClass}")
	private String jdbcDriver;

	@Value("${datasource.user}")
	private String username;

	@Value("${datasource.password}")
	private String password;

	@Value("${datasource.jdbcUrl}")
	private String jdbcUrl;

	@Value("${datasource.maxIdle}")
    private String maxIdle;

	@Value("${datasource.minIdle}")
    private String minIdle;

    @Value("${datasource.maxWait}")
    private String maxWait;

    @Value("${datasource.validationQuery}")
    private String validationQuery;

    @Value("${datasource.maxActive}")
    private int maxActive;

    @Value("${datasource.testOnBorrow}")
    private boolean testOnBorrow;

    @Value("${datasource.testOnReturn}")
    private boolean testOnReturn;

	@Value("${datasource.testWhileIdle}")
    private boolean testWhileIdle;

	@Value("${datasource.timeBetweenEvictionRunsMillis}")
    private long timeBetweenEvictionRunsMillis;

    @Value("${datasource.minEvictableIdleTimeMillis}")
	private long minEvictableIdleTimeMillis;

	@Bean
	public DataSource dataSource() {
		DruidDataSource ds = new DruidDataSource();
		ds.setDriverClassName(this.jdbcDriver);
		ds.setUsername(username);
		ds.setPassword(password);
		ds.setUrl(jdbcUrl);
		ds.setMaxActive(maxActive);
		ds.setValidationQuery(validationQuery);
		ds.setTestOnBorrow(testOnBorrow);
		ds.setTestOnReturn(testOnReturn);
		ds.setTestWhileIdle(testWhileIdle);
		ds.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
		ds.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
		return ds;
	}


	public Resource[] getResource( String basePackage, String pattern ) throws IOException {
		String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
				+ ClassUtils.convertClassNameToResourcePath(new StandardEnvironment()
				.resolveRequiredPlaceholders(basePackage)) + "/" + pattern;
		Resource[] resources = new PathMatchingResourcePatternResolver().getResources(packageSearchPath);
        return resources;
	}


	@Bean
	public SqlSessionFactory sqlSessionFactory() throws Exception {
		log.debug("> sqlSessionFactory");
		final SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
		sqlSessionFactory.setDataSource(dataSource());
		sqlSessionFactory.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
		sqlSessionFactory.setFailFast(true);
		sqlSessionFactory.setMapperLocations(getResource("mappers", "**/*.xml"));
		/*SqlMonitorManager sqlMonitorManager = new SqlMonitorManager();
		Properties properties = new Properties();
		properties.setProperty("show_sql", "true");
		sqlMonitorManager.setProperties(properties);

		PageInterceptor pageInterceptor = new PageInterceptor();
		Properties property = new Properties();
		properties.setProperty("databaseType", "mysql");
		pageInterceptor.setProperties(property);
		sqlSessionFactory.setPlugins(new Interceptor[]{sqlMonitorManager, pageInterceptor});*/
		return sqlSessionFactory.getObject();
	}

	@Bean
	public DataSourceTransactionManager transactionManager() {
		log.debug("> transactionManager");
		return new DataSourceTransactionManager(dataSource());
	}
}
